<template>
  <div class="cate-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ pageTitle }}</h3>
          <el-button type="primary" @click="handleAdd">添加{{ titleLabel }}</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="cateList" border style="width: 100%">
        <el-table-column prop="id" label="ID号" width="80" align="center" />
        <el-table-column prop="title" :label="titleLabel" />
        <el-table-column v-if="hasNameField" prop="name" :label="nameLabel" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <span v-if="row.status === 1" class="green">正常</span>
            <span v-else class="yellow">禁用</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)" type="primary">查看</el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              size="small"
              v-if="row.status === 1"
              @click="handleDisable(row)"
              type="danger"
            >
              禁用
            </el-button>
            <el-button size="small" v-else @click="handleEnable(row)" type="success">
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 抽屉组件 - 用于新增/编辑 -->
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      direction="rtl"
      size="400px"
      @close="handleDrawerClose"
    >
      <el-form :model="cateForm" :rules="cateRules" ref="cateFormRef" label-width="80px">
        <el-form-item :label="titleLabel" prop="title">
          <el-input v-model="cateForm.title" :placeholder="`请输入${titleLabel}`" />
        </el-form-item>

        <el-form-item v-if="hasNameField" :label="nameLabel" prop="name">
          <el-input v-model="cateForm.name" :placeholder="`请输入${nameLabel}`" />
        </el-form-item>

        <el-form-item style="margin-top: 30px">
          <el-button type="primary" @click="submitCate" style="width: 100%">确认</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 抽屉组件 - 用于查看 -->
    <el-drawer v-model="viewDrawerVisible" title="详情查看" direction="rtl" size="400px">
      <div class="detail-info">
        <p>
          <strong>ID号:</strong>
          {{ currentRow?.id }}
        </p>
        <p>
          <strong>{{ titleLabel }}:</strong>
          {{ currentRow?.title }}
        </p>
        <p v-if="hasNameField">
          <strong>{{ nameLabel }}:</strong>
          {{ currentRow?.name || '无' }}
        </p>
        <p>
          <strong>状态:</strong>
          {{ currentRow?.status === 1 ? '正常' : '禁用' }}
        </p>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { getEnterpriseList, saveEnterprise, setEnterpriseStatus } from '@/api/home/cate'

  // 数据相关
  interface CateItem {
    id: number
    title: string
    name?: string
    status: number
    [key: string]: any
  }

  const cateList = ref<CateItem[]>([])
  const loading = ref(false)
  const route = useRoute()

  // 抽屉相关
  const drawerVisible = ref(false)
  const drawerTitle = ref('')
  const isEdit = ref(false)
  const viewDrawerVisible = ref(false)
  const currentRow = ref<any>(null)

  // 表单数据
  const cateForm = reactive({
    id: 0,
    title: '',
    name: '',
  })

  // 表单验证规则
  const cateRules = {
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  }

  // 表格列配置
  const tableColumns = computed(() => {
    const columns: Array<{
      prop: string
      label: string
      width?: number | string
      align?: string
      slot?: string
      formatter?: (row: any, column: any, cellValue: any, index: number) => string
    }> = [
      { prop: 'id', label: 'ID号', width: 80, align: 'center' },
      { prop: 'title', label: titleLabel.value },
    ]

    if (hasNameField.value) {
      columns.push({ prop: 'name', label: nameLabel.value })
    }

    columns.push({
      prop: 'status',
      label: '状态',
      width: 80,
      align: 'center',
      slot: 'status',
    })

    return columns
  })

  // 表单引用
  const cateFormRef = ref()

  // 页面配置映射
  const pageConfig = computed(() => {
    const configMap: any = {
      enterprise: {
        title: '企业管理',
        addLabel: '添加企业',
        titleLabel: '企业名称',
        nameLabel: '企业编码',
        hasName: true,
      },
      job: {
        title: '岗位管理',
        addLabel: '添加岗位',
        titleLabel: '岗位名称',
        nameLabel: '',
        hasName: false,
      },
      level: {
        title: '职级管理',
        addLabel: '添加职级',
        titleLabel: '职级名称',
        nameLabel: '',
        hasName: false,
      },
      process: {
        title: '流程管理',
        addLabel: '添加流程',
        titleLabel: '流程名称',
        nameLabel: '',
        hasName: false,
      },
    }

    return configMap[route.params.type as string] || configMap.enterprise
  })

  // 页面标题
  const pageTitle = computed(() => pageConfig.value.title)

  // 移除未使用的添加按钮标签计算属性

  // 标题字段标签
  const titleLabel = computed(() => pageConfig.value.titleLabel)

  // 名称字段标签
  const nameLabel = computed(() => pageConfig.value.nameLabel)

  // 是否有名称字段
  const hasNameField = computed(() => pageConfig.value.hasName)

  // 获取列表数据
  const getCateList = async () => {
    try {
      loading.value = true
      const currentType = route.params.type
      console.log('当前路由类型:', currentType)
      console.log('当前路由路径:', route.path)

      let response: any
      switch (currentType) {
        case 'enterprise':
          response = await getEnterpriseList()
          break
        case 'job':
          // 这里应该调用对应的API
          break
        case 'level':
          // 这里应该调用对应的API
          break
        case 'process':
          // 这里应该调用对应的API
          break
        default:
          // 默认也尝试获取企业列表，防止路由参数问题
          console.log('使用默认企业列表API')
          response = await getEnterpriseList()
      }

      // 打印完整响应用于调试
      console.log('API响应:', response)

      // 注意：由于响应拦截器已经将response.data作为返回值，
      // 所以这里直接使用response.code和response.data
      if (response && response.code === 0) {
        // 简化数据处理逻辑
        if (response.data) {
          if (Array.isArray(response.data)) {
            console.log('数据是数组，长度:', response.data.length)
            cateList.value = response.data
          } else if (typeof response.data === 'object' && response.data.list) {
            // 处理分页数据格式
            console.log('使用list属性，长度:', response.data.list.length)
            cateList.value = response.data.list
          } else {
            // 如果数据既不是数组也没有list属性，可能是单条数据
            console.log('数据是单条记录，转换为数组')
            cateList.value = [response.data]
          }
        } else {
          console.warn('API返回数据为空')
          cateList.value = []
        }

        // 再次确认数据状态
        console.log('最终表格数据长度:', cateList.value.length)
        if (cateList.value.length === 0) {
          console.log('没有找到有效数据')
        }
      } else {
        ElMessage.error(response?.data?.msg || '获取列表失败')
        console.error('API返回错误:', response)
      }
    } catch (error) {
      console.error('API请求错误:', error)
      ElMessage.error('获取列表失败')
    } finally {
      loading.value = false
    }
  }

  // 处理添加分类 (确保没有重复声明)
  const handleAdd = () => {
    drawerTitle.value = `新增${pageConfig.value.titleLabel}`
    isEdit.value = false

    // 重置表单
    Object.assign(cateForm, {
      id: 0,
      title: '',
      name: '',
    })

    drawerVisible.value = true
  }

  // 处理编辑分类
  const handleEdit = (row: any) => {
    drawerTitle.value = `编辑${pageConfig.value.titleLabel}`
    isEdit.value = true

    // 填充表单数据
    Object.assign(cateForm, row)

    drawerVisible.value = true
  }

  // 查看分类详情
  const handleView = (row: any) => {
    currentRow.value = row
    viewDrawerVisible.value = true
  }

  // 禁用分类
  const handleDisable = async (row: any) => {
    try {
      const currentType = route.params.type
      let response: any

      switch (currentType) {
        case 'enterprise':
          response = await setEnterpriseStatus({ id: row.id, status: 0 })
          break
        // 其他类型处理
        default:
          response = await setEnterpriseStatus({ id: row.id, status: 0 })
      }

      if (response.data.code === 0) {
        ElMessage.success('禁用成功')
        await getCateList()
      } else {
        ElMessage.error(response.data.msg || '禁用失败')
      }
    } catch (error) {
      ElMessage.error('禁用失败')
    }
  }

  // 启用分类
  const handleEnable = async (row: any) => {
    try {
      const currentType = route.params.type
      let response: any

      switch (currentType) {
        case 'enterprise':
          response = await setEnterpriseStatus({ id: row.id, status: 1 })
          break
        // 其他类型处理
        default:
          response = await setEnterpriseStatus({ id: row.id, status: 1 })
      }

      if (response.data.code === 0) {
        ElMessage.success('启用成功')
        await getCateList()
      } else {
        ElMessage.error(response.data.msg || '启用失败')
      }
    } catch (error) {
      ElMessage.error('启用失败')
    }
  }

  // 提交分类信息
  const submitCate = async () => {
    if (!cateFormRef.value) return

    try {
      await cateFormRef.value.validate()

      const currentType = route.params.type
      let response: any

      const params = {
        id: cateForm.id,
        title: cateForm.title,
        name: cateForm.name,
      }

      switch (currentType) {
        case 'enterprise':
          response = await saveEnterprise(params)
          break
        // 其他类型处理
        default:
          response = await saveEnterprise(params)
      }

      if (response.data.code === 0) {
        ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
        drawerVisible.value = false
        await getCateList()
      } else {
        ElMessage.error(response.data.msg || (isEdit.value ? '编辑失败' : '添加失败'))
      }
    } catch (error) {
      ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
    }
  }

  // 抽屉关闭时重置表单
  const handleDrawerClose = () => {
    if (cateFormRef.value) {
      cateFormRef.value.resetFields()
    }
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getCateList()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .green {
    color: #67c23a;
  }

  .yellow {
    color: #e6a23c;
  }

  .detail-info {
    padding: 20px;
  }

  .detail-info p {
    margin-bottom: 16px;
    line-height: 1.8;
  }

  .detail-info strong {
    color: #303133;
    margin-right: 8px;
  }

  /* 优化按钮间距 */
  :deep(.el-button + .el-button) {
    margin-left: 10px;
  }
</style>
